﻿#include "mediaDemuxing.h"
#include "error.h"
#include "global.h"

#include <QDebug>
class mediaDemuxingPrivate {
public:
    AVFormatContext *ic = NULL;
};

#include <crtdbg.h>
#include <assert.h>

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

mediaDemuxing::mediaDemuxing(QObject *parent) :
    QObject(parent), d(new mediaDemuxingPrivate)
{
    //注册ffmpeg
    av_register_all();
    avformat_network_init();
}

bool mediaDemuxing::open(QString mediaUrl)
{
	if ("" == mediaUrl)
        return false;

    int r = -1;

    // 打开输入路径
    if ((r = avformat_open_input(&d->ic, mediaUrl.toStdString().c_str(), NULL, NULL)) < 0) {
        char buf[64] = {0};
		qDebug() << mediaUrl.toStdString().c_str();
        _errstr = QString(av_make_error_string(buf, 64, r));
        return false;
    }

    // 读取文件的一些包以获取媒体信息
    if ((r = avformat_find_stream_info(d->ic, NULL)) < 0) {
        char buf[64] = {0};
        _errstr = QString(av_make_error_string(buf, 64, r));
        return false;
    }

    return true;
}

AVFormatContext *mediaDemuxing::getFormat()
{
    return d->ic;
}

mediaDemuxing::~mediaDemuxing()
{
    if(d->ic)
        avformat_close_input(&d->ic);
	delete d;
}
